//package com.example.rwq_test;
//
//import org.eclipse.paho.mqttv5.client.IMqttToken;
//import org.eclipse.paho.mqttv5.client.MqttCallback;
//import org.eclipse.paho.mqttv5.client.MqttClient;
//import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
//import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
//import org.eclipse.paho.mqttv5.common.MqttException;
//import org.eclipse.paho.mqttv5.common.MqttMessage;
//import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.web.socket.config.annotation.EnableWebSocket;
//import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
//import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//import org.springframework.web.socket.handler.TextWebSocketHandler;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.TextMessage;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.UUID;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.CopyOnWriteArrayList;
//import java.util.logging.Level;
//import java.util.logging.Logger;
//
//@SpringBootApplication
//@EnableWebSocket
//@EnableScheduling
//public abstract class WebRtcServer1 implements WebSocketConfigurer, MqttCallback {
//
//    private static final Logger LOGGER = Logger.getLogger(WebRtcServer1.class.getName());
//    private static final String MQTT_BROKER = "tcp://localhost:1883";
//    private static final String MQTT_USERNAME = "admin";
//    private static final String MQTT_PASSWORD = "public123";
//    private static final String OFFER_TOPIC = "webrtc/offer";
//    private static final String ANSWER_TOPIC = "webrtc/answer";
//
//    private MqttClient mqttClient;
//    private final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
//    private final String clientId = "java-client-" + UUID.randomUUID().toString().substring(0, 8);
//    private boolean subscribed = false;
//
//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
//    }
//
//    @PostConstruct
//    public void initMqtt() {
//        LOGGER.info("Initializing MQTT client with ID: " + clientId);
//        try {
//            mqttClient = new MqttClient(MQTT_BROKER, clientId);
//            MqttConnectionOptions options = new MqttConnectionOptions();
//            options.setAutomaticReconnect(true);
//            options.setPassword(MQTT_PASSWORD.getBytes(StandardCharsets.UTF_8));
//            options.setUserName(MQTT_USERNAME);
//            options.setCleanStart(true);
//            options.setConnectionTimeout(10);
//            options.setKeepAliveInterval(60);
//
//            mqttClient.setCallback(this);
//            LOGGER.info("Connecting to MQTT broker...");
//            mqttClient.connect(options);
//            LOGGER.info("MQTT connection established");
//
//            // 初始订阅
//            subscribeToAnswerTopic();
//        } catch (MqttException e) {
//            LOGGER.log(Level.SEVERE, "MQTT initialization failed: " + e.getMessage(), e);
//        }
//    }
//
//    private void subscribeToAnswerTopic() {
//        try {
//            if (mqttClient != null && mqttClient.isConnected()) {
//                LOGGER.info("Subscribing to topic: " + ANSWER_TOPIC);
//                mqttClient.subscribe(ANSWER_TOPIC, 1);
//                subscribed = true;
//                LOGGER.info("Subscribed to " + ANSWER_TOPIC + " successfully");
//            }
//        } catch (MqttException e) {
//            LOGGER.log(Level.SEVERE, "Subscription failed: " + e.getMessage(), e);
//            subscribed = false;
//        }
//    }
//
//    @Scheduled(fixedRate = 30000)
//    public void cleanDeadSessions() {
//        LOGGER.fine("Cleaning dead WebSocket sessions");
//        sessions.removeIf(session -> {
//            if (!session.isOpen()) {
//                LOGGER.info("Removing closed session: " + session.getId());
//                return true;
//            }
//            return false;
//        });
//        LOGGER.fine("Active sessions: " + sessions.size());
//    }
//
//    @PreDestroy
//    public void closeResources() {
//        LOGGER.info("Closing application resources...");
//
//        // 关闭所有WebSocket会话
//        sessions.forEach(session -> {
//            try {
//                if (session.isOpen()) {
//                    session.close();
//                    LOGGER.info("Closed WebSocket session: " + session.getId());
//                }
//            } catch (Exception e) {
//                LOGGER.log(Level.WARNING, "Error closing WebSocket session: " + e.getMessage(), e);
//            }
//        });
//        sessions.clear();
//
//        // 关闭MQTT连接
//        try {
//            if (mqttClient != null && mqttClient.isConnected()) {
//                mqttClient.disconnect();
//                mqttClient.close();
//                LOGGER.info("MQTT client disconnected");
//            }
//        } catch (MqttException e) {
//            LOGGER.log(Level.SEVERE, "Error disconnecting MQTT: " + e.getMessage(), e);
//        }
//    }
//
//    // MQTT回调接口实现
//    @Override
//    public void disconnected(MqttDisconnectResponse disconnectResponse) {
//        LOGGER.warning("MQTT disconnected: " + disconnectResponse.getReasonString());
//        subscribed = false;
//    }
//
//    @Override
//    public void mqttErrorOccurred(MqttException exception) {
//        LOGGER.log(Level.SEVERE, "MQTT error: " + exception.getMessage(), exception);
//    }
//
//    @Override
//    public void deliveryComplete(IMqttToken token) {
//        // 消息传递完成回调
//    }
//
//    @Override
//    public void messageArrived(String topic, MqttMessage message) {
//        if (!ANSWER_TOPIC.equals(topic)) return;
//
//        String payload = new String(message.getPayload());
//        if (LOGGER.isLoggable(Level.FINE)) {
//            LOGGER.fine("Received MQTT message on " + topic + ": " + payload.substring(0, Math.min(payload.length(), 100)) + "...");
//        }
//
//        // 使用会话快照避免并发修改
//        List<WebSocketSession> activeSessions = new ArrayList<>(sessions);
//        for (WebSocketSession session : activeSessions) {
//            try {
//                if (session.isOpen()) {
//                    if (LOGGER.isLoggable(Level.FINE)) {
//                        LOGGER.fine("Sending to WebSocket session: " + session.getId());
//                    }
//                    session.sendMessage(new TextMessage(payload));
//                } else {
//                    LOGGER.info("Session " + session.getId() + " is closed, removing");
//                    sessions.remove(session);
//                }
//            } catch (Exception e) {
//                LOGGER.log(Level.WARNING, "Error sending to WebSocket: " + e.getMessage(), e);
//                sessions.remove(session);
//            }
//        }
//    }
//
//    @Override
//    public void authPacketArrived(int reasonCode, MqttProperties properties) {
//        // 认证包到达处理
//    }
//
//    public class WebSocketHandler extends TextWebSocketHandler {
//        @Override
//        public void afterConnectionEstablished(WebSocketSession session) {
//            LOGGER.info("WebSocket connected: " + session.getId());
//            sessions.add(session);
//        }
//
//        @Override
//        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//            String payload = message.getPayload();
//            if (LOGGER.isLoggable(Level.FINE)) {
//                LOGGER.fine("Received from WebSocket: " + payload.substring(0, Math.min(payload.length(), 100)) + "...");
//            }
//
//            if (mqttClient != null && mqttClient.isConnected()) {
//                MqttMessage mqttMsg = new MqttMessage(payload.getBytes());
//                mqttMsg.setQos(1); // 设置QoS为1
//                mqttClient.publish(OFFER_TOPIC, mqttMsg);
//                if (LOGGER.isLoggable(Level.FINE)) {
//                    LOGGER.fine("Published to MQTT topic: " + OFFER_TOPIC);
//                }
//            } else {
//                LOGGER.warning("MQTT client not connected, message dropped");
//            }
//        }
//
//        @Override
//        public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) {
//            LOGGER.info("WebSocket closed: " + session.getId() + ", reason: " + status.getReason());
//            sessions.remove(session);
//        }
//
//        @Override
//        public void handleTransportError(WebSocketSession session, Throwable exception) {
//            LOGGER.log(Level.WARNING, "WebSocket error: " + session.getId() + " - " + exception.getMessage(), exception);
//            sessions.remove(session);
//        }
//    }
//
//    public static void main(String[] args) {
//        LOGGER.setLevel(Level.INFO);
//        LOGGER.info("Starting WebRTC signaling server");
//        SpringApplication.run(WebRtcServer.class, args);
//    }
//}